package com.ding.easycontroller.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class ClassLoadUtils {

    private static class MyClassLoader extends URLClassLoader {
        private MyClassLoader(ClassLoader parent) {
            super(new URL[0], parent);
        }
        Class<?> readClassFromByteArray(byte[] bytes) {
            try {
                return defineClass(null, bytes, 0, bytes.length);
            } catch (Error e) {
                e.printStackTrace();
                return null;
            }
        }
        @Override
        public void addURL(URL url) {
            super.addURL(url);
        }
    }

    private static MyClassLoader myClassLoader;

    public static void setParrentClassLoader(ClassLoader loader) {

        try {
            myClassLoader = new MyClassLoader(loader);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static Class<?> loadClassByBateArray(byte[] bytes) {
        return myClassLoader.readClassFromByteArray(bytes);
    }

    public static List<Class<?>> loadClassFromJarFile(File file) {

              /*  file = new File("C:\\Users\\dinglei\\Desktop\\ec\\basePlugins\\target\\basePlugins-1.0-SNAPSHOT-jar-with-dependencies.jar");
*/
        List<Class<?>> r = new ArrayList<>();
        try {
            JarFile jarFile = new JarFile(file);

            //载入包
            URL url = file.toURI().toURL();//?无法载入
            myClassLoader.addURL(url);

            Enumeration<JarEntry> files = jarFile.entries();
            while (files.hasMoreElements()) {
                JarEntry jarEntry = files.nextElement();

                if (jarEntry.getName().matches("^(.*/)?easycontroller/plugin/expand/(.*)\\.class$")) {

                    System.out.println("加载"+jarEntry.getName());

                    InputStream inputStream = jarFile.getInputStream(jarEntry);
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    byte[] buff = new byte[1024];
                    int len;
                    while ((len = inputStream.read(buff)) != -1) {
                        byteArrayOutputStream.write(buff, 0, len);
                    }
                    inputStream.close();
                    Class<?> aClass = loadClassByBateArray(byteArrayOutputStream.toByteArray());
                    if (aClass != null) {
                        r.add(aClass);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Collections.emptyList();
        }
        return r;
    }



}
